{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import Spider\n",
    "\n",
    "def highlight(text: str, keyword: str):\n",
    "    idx = text.lower().find(keyword.lower())\n",
    "    result = text\n",
    "    if idx >= 0:\n",
    "        ori_word = text[idx:idx+(len(keyword))]\n",
    "        result = text.replace(ori_word, f'*{ori_word}*')\n",
    "    return result\n",
    "\n",
    "def score(item, keyword: str):\n",
    "    title_score = item[1].lower().count(keyword.lower())\n",
    "    content_score = item[2].lower().count(keyword.lower())\n",
    "    score_result = title_score * 5 + content_score * 3\n",
    "    return score_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "class MySearcherC5V1:\n",
    "    \"\"\"加入缓存的版本\"\"\"\n",
    "    def __init__(self, scale: int=1):\n",
    "        self.docs = list()\n",
    "        self.load_data()\n",
    "        if scale > 1:\n",
    "            self.docs *= scale  # 文档规模倍增，用于测试搜索速度\n",
    "        self.cache = dict()\n",
    "\n",
    "    def load_data(self, data_file_name='./news_list.pkl'):\n",
    "        if os.path.exists(data_file_name):\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "        else:\n",
    "            Spider.pickle_save(data_file_name)\n",
    "            self.docs = Spider.pickle_load(data_file_name)\n",
    "\n",
    "    def search(self, keyword):\n",
    "        keyword = keyword.lower()\n",
    "        if keyword not in self.cache:\n",
    "            count = 0\n",
    "            sorted_result = list()\n",
    "            for item in self.docs:\n",
    "                if keyword in (item[1] + item[2]).lower():\n",
    "                    sorted_result.append([count, score(item, keyword), item[1]])\n",
    "                count += 1\n",
    "            sorted_result.sort(key=lambda x: x[1], reverse=True)\n",
    "            self.cache[keyword] = sorted_result\n",
    "        else:\n",
    "            sorted_result = self.cache[keyword]\n",
    "        return sorted_result\n",
    "\n",
    "    def render_search_result(self, keyword):\n",
    "        count = 0\n",
    "        for item in self.search(keyword):\n",
    "            count += 1\n",
    "            print(f'{count}[{item[1]}] {highlight(self.docs[item[0]][1], keyword)}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "class MySearcherC5V2(MySearcherC5V1):\n",
    "    \"\"\"加入预热功能的版本\"\"\"\n",
    "    def __init__(self, scale=1):\n",
    "        super().__init__(scale)\n",
    "        self.vocab = {'华为', '手机', 'tiktok'}   # 手动建立一个预热关键词集合\n",
    "        self.build_cache()\n",
    "\n",
    "    def build_cache(self):\n",
    "        \"\"\"在用户使用之前，提前搜索一遍vocab里面的内容，进行预热\"\"\"\n",
    "        for word in self.vocab:\n",
    "            self.search(word)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 412 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_1x_v1 = MySearcherC5V1()\n",
    "searcher_10x_v1 = MySearcherC5V1(scale=10)\n",
    "searcher_100x_v1 = MySearcherC5V1(scale=100)\n",
    "searcher_1000x_v1 = MySearcherC5V1(scale=1000)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 14 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_1x_v2 = MySearcherC5V2(scale=1)\n",
    "searcher_10x_v2 = MySearcherC5V2(scale=10)\n",
    "searcher_100x_v2 = MySearcherC5V2(scale=100)\n",
    "searcher_1000x_v2 = MySearcherC5V2(scale=1000)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 3.99 ms\n",
      "Wall time: 33.9 ms\n",
      "Wall time: 363 ms\n",
      "Wall time: 3.87 s\n",
      "Wall time: 41.9 ms\n"
     ]
    }
   ],
   "source": [
    "# 搜索时间随数据量增加而变化情况\n",
    "%time r = searcher_1x_v1.search('华为')\n",
    "%time r = searcher_10x_v1.search('华为')\n",
    "%time r = searcher_100x_v1.search('华为')\n",
    "%time r = searcher_1000x_v1.search('华为')\n",
    "\n",
    "%time r = searcher_10x_v1.search('苹果')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 0 ns\n",
      "Wall time: 0 ns\n"
     ]
    }
   ],
   "source": [
    "# 搜素时间随搜索次数增加而变化情况\n",
    "%time for i in range(10):r = searcher_10x_v1.search('华为')\n",
    "%time for i in range(100):r = searcher_10x_v1.search('华为')\n",
    "# 加入缓存功能后，重复查询耗费时间将极大缩短"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "outputs": [],
   "source": [
    "import jieba\n",
    "\n",
    "class MySearcherC5V3(MySearcherC5V2):\n",
    "    \"\"\"对文档进行分词后作为预热关键词\"\"\"\n",
    "    def build_cache(self):\n",
    "        \"\"\"用分词（用文档过滤词库）的方式初始化缓存\"\"\"\n",
    "        for doc in self.docs:\n",
    "            for word in jieba.cut(doc[1]+' '+doc[2], cut_all=True):\n",
    "                self.search(word)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\10633\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 0.605 seconds.\n",
      "Prefix dict has been built successfully.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 1min 29s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "searcher_1x_v3 = MySearcherC5V3()\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}